import { getPageListData } from '@/service/main/system/system'
import { createStore, Store, useStore as useStoreVux } from 'vuex'
import login from './login/login'
import dashboard from './main/analysis/dashboard'
import system from './main/system/system'
import { IRootState, IStoreType } from './type'
const store = createStore<IRootState>({
  state() {
    return {
      name: '',
      departmentList: [],
      roleList: [],
      menuList: []
    }
  },
  getters: {},
  mutations: {
    CHANGE_DEPARTMENT_LIST(state, list) {
      state.departmentList = list
    },
    CHANGE_ROLE_LIST(state, list) {
      state.roleList = list
    },
    CHANGE_MENU_LIST(state, list) {
      state.menuList = list
    }
  },
  actions: {
    async getInitialDataAction({ commit }) {
      // 请求部门数据
      const departmentResult = await getPageListData('/department/list', {
        offset: 0,
        size: 100
      })
      const { list: departmentList } = departmentResult.data
      // 请求角色数据
      const roleResult = await getPageListData('/role/list', {
        offset: 0,
        size: 100
      })
      const { list: roleList } = roleResult.data
      // 请求全部权限数据
      const menusResult = await getPageListData('/menu/list', {})
      const { list: menuList } = menusResult.data

      commit('CHANGE_DEPARTMENT_LIST', departmentList)
      commit('CHANGE_ROLE_LIST', roleList)
      commit('CHANGE_MENU_LIST', menuList)
    }
  },
  modules: {
    login,
    system,
    dashboard
  }
})
export default store

export function setupStore() {
  store.dispatch('login/loadLocalLogin')
  store.dispatch('getInitialDataAction')
}

export function useStore(): Store<IStoreType> {
  return useStoreVux()
}
